package theory;

import java.io.File;
import java.io.PrintWriter;

import org.antlr.runtime.ANTLRStringStream;
import org.antlr.runtime.CommonTokenStream;
import org.antlr.runtime.Lexer;
import org.antlr.runtime.RecognitionException;
import org.antlr.runtime.tree.CommonTree;
import org.antlr.runtime.tree.CommonTreeNodeStream;

import compiler.DotDump;
import compiler.antlr.REAST;
import compiler.antlr.RELexer;
import compiler.antlr.REParser;
import compiler.grammar.NonTerminal;
import compiler.grammar.Production;
import compiler.grammar.Terminal;
import compiler.parser.lalr.LALRState;
import compiler.scanner.dfa.DFAGen;
import compiler.scanner.dfa.DFAState;
import compiler.scanner.nfa.NFAItem;
import compiler.scanner.nfa.NFAState;

public class TestDFAIntersection
{
    private static DFA getMinimizedDfaFromRegex(String regex, String statePrefix) throws RecognitionException
    {
        ANTLRStringStream stream = new ANTLRStringStream(regex);

        Lexer lexer = new RELexer(stream);
        CommonTokenStream tokenStream = new CommonTokenStream(lexer);
        REParser _inputParser = new REParser(tokenStream);
        REParser.start_return tree = _inputParser.start();
        CommonTree commonTree = (CommonTree)tree.getTree();
        CommonTreeNodeStream nodeStream = new CommonTreeNodeStream(commonTree);
        NFAItem g = new REAST(nodeStream).start("M1");

        DFAGen dfagen = new DFAGen(g.getStartState());
        DFAState dfa = dfagen.getMinimizedDfa();
        return new DFA(dfa);
    }

    public static void main(String[] args) throws Throwable
    {
        Terminal.reset();
        NonTerminal.reset();
        Production.reset();
        LALRState.reset();
        DFAState.reset();
        NFAState.reset();

        DFA q = getMinimizedDfaFromRegex("(00)*|11", "q");

        DFA p = getMinimizedDfaFromRegex("110", "p");

        // The case "any string except 'a'" should be easy to do if we always put a transition to a "bottom" state except having a partial transition function.

        DFA dfa = q;//.complement();

        System.out.println();
        String dump = DotDump.dumpDot(dfa);
        System.out.println(dump);

        // TODO next: implement GNFA algorithm to convert DFA to a regular expression

        PrintWriter pw = new PrintWriter("./testcases/dfa_intersection.dot");
        pw.println(dump);
        pw.close();
        new ProcessBuilder("./translateGraphs.sh").directory(new File("./testcases")).start().waitFor();
    }
}
